package com.yunqian.util.message;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.yunqian.constant.AliyunSmsKey;
import lombok.extern.log4j.Log4j2;

/**
 * @author czy
 * @describe
 * @date 2018/10/22
 */
@Log4j2
public class AliyunSmsUtil {

    public static boolean sendSMSMessage(String mobile, String templateParam, String templateCode){
        try {
            SendSmsResponse response = sendSms(mobile, templateParam, templateCode);
            if("OK".equals(response.getCode()) && "OK".equals(response.getMessage())){
                return true;
            }
        } catch (ClientException e) {
            log.warn("发送短信失败,原因：" + e.getMessage());
        }
        return false;
    }

    public static SendSmsResponse sendSms(String mobile, String templateParam, String templateCode) throws ClientException {
        // 可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        // 初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", AliyunSmsKey.APP_KEY, AliyunSmsKey.SECRET);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", AliyunSmsKey.PRODUCT, AliyunSmsKey.DOMAIN);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        // 组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        // 必填:待发送手机号
        request.setPhoneNumbers(mobile);
        // 必填:短信签名-可在短信控制台中找到
        request.setSignName(AliyunSmsKey.SIGN_NAME);
        // 必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        // 设置模板参数 例： "{\"name\":\"Tom\", \"code\":\"123\"}"
        request.setTemplateParam(templateParam);
        // 此处可能会抛出异常，注意
        return acsClient.getAcsResponse(request);
    }

}
